package utils;

import groovy.lang.Closure;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.Play;
import play.mvc.Router;
import play.templates.FastTags;
import play.templates.GroovyTemplate;
import play.vfs.VirtualFile;

import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhangzc
 * @since 2017/7/4
 */
public class XTag extends FastTags {

    private static final Map<String, String> hrefCache = new ConcurrentHashMap();

    public static void _href(Map<?, ?> args, Closure body, PrintWriter out, GroovyTemplate.ExecutableTemplate template, int fromLine){
        if (!args.containsKey("arg") || args.get("arg") == null) {
            // do nothing
            return;
        }
        String action = (String) args.get("arg");

        String key = String.format("href-%s", action);

        String result = hrefCache.get(key);
        if(StringUtils.isNotEmpty(result)){
            out.write(result);
            return;
        }
        try{
            StringBuilder sb = new StringBuilder();
            VirtualFile file = Play.getVirtualFile(action);
            String href = Router.reverseWithCheck(action, file, false);
            String fileSig = String.valueOf(file.lastModified());

            sb.append(CdnUtil.getCdn());
            sb.append(href);
            sb.append("?_=");
            sb.append(fileSig);

            hrefCache.put(key, sb.toString());
            out.write(sb.toString());
        }catch (Exception e){
            Logger.error(e, "ERROR in href");
            out.write(CdnUtil.getCdn() + action);
        }
    }
}
